﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using LogicAndDB;
using Common;
using System.Text.RegularExpressions;
namespace AccountManagement.code
{
    public class MyMemberShipProvider:MembershipProvider
    {
        System.Collections.Specialized.NameValueCollection _config;
        public override int MaxInvalidPasswordAttempts
        {
            get { return int.Parse(_config["maxInvalidPasswordAttempts"]); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return int.Parse(_config["minRequiredNonalphanumericCharacters"]); }
        }


        public override int MinRequiredPasswordLength
        {
            get { return int.Parse(_config["minRequiredPasswordLength"]); }
        }

        public override int PasswordAttemptWindow
        {
            get { return int.Parse(_config["passwordAttemptWindow"]); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Clear; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        string _applicationName;
        public override string ApplicationName
        {
            get
            {
                return _applicationName;
            }
            set
            {
                _applicationName = value;
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            DBContainer db = DBContainer.Instance;
            CUser aUser = CUser.GetUserByName(username);
            if (aUser == null)
                return false;
            if (!aUser.IsPasswordCorrect(oldPassword))
                return false;

            aUser.SetNewPassword(newPassword);
            return db.CommitChanges();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            DBContainer db = DBContainer.Instance;


            Regex reg = new Regex(@"(?<name>\S+)@(?<domain>\S+)");
            Match aMatch = reg.Match(email);
            if (!aMatch.Success)
            {
                status = MembershipCreateStatus.InvalidEmail;
                return null;
            }

            if (CUser.IsEmailDuplicated(email))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            if (CUser.IsNameDuplicated(username))
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }
            if (password.Length < MinRequiredPasswordLength)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }
          
            CUser aUser = new CUser();
            aUser.Name = username;
            aUser.Mail = email;
            aUser.Password = password;
            aUser.Activated = false;
            aUser.LastLogin = DateTime.Now;
            aUser.ActivationKey = "no key";
            CUser.AddNewUser(aUser);
            
            status = MembershipCreateStatus.Success;
            return GetMembershipUser(username, email, DateTime.Now);

        }
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }
        public override string Description
        {
            get
            {
                return base.Description;
            }
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }

        }
        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }
        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            CUser usr= CUser.GetUserByMail(email);
            if (usr == null)
                return "";

            return usr.Name;
        }


        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            ApplicationName = config["applicationName"];
            _config = config;
        }
        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            return CUser.Auth(username,password);
        }
        /// <summary>
        /// Gets membership user.
        /// </summary>
        /// <param name="userName">
        /// The user name.
        /// </param>
        /// <param name="email">
        /// The email.
        /// </param>
        /// <param name="lastLogin">
        /// The last login.
        /// </param>
        /// <returns>
        /// A MembershipUser.
        /// </returns>
        private MembershipUser GetMembershipUser(string userName, string email, DateTime lastLogin)
        {
            var user = new MembershipUser(
                this.Name, // Provider name
                userName, // Username
                userName, // providerUserKey
                email, // Email
                string.Empty, // passwordQuestion
                string.Empty, // Comment
                true, // approved
                false, // isLockedOut
                DateTime.Now, // creationDate
                lastLogin, // lastLoginDate
                DateTime.Now, // lastActivityDate
                DateTime.Now, // lastPasswordChangedDate
                new DateTime(1980, 1, 1)); // lastLockoutDate
            return user;
        }
    }
}